const router = require('koa-router')()
const path = require("path");
var svgCaptcha = require('svg-captcha');
svgCaptcha.height = 40;
var nowCaptcha;
var jwt = require("jsonwebtoken");
const { IncomingForm } = require('formidable');
const mykey = "shidaihaodang";
const formidable = require("formidable");
const fs = require("fs");
const cheakToken = require("../static/checkToken");
const url = path.join(__dirname, "../public/upload");
const portraitUrl = path.join(__dirname, "../public/portrait");

const selectAllImagesQuery = "SELECT image_name FROM image";
const uploadDirPath = path.join(__dirname, "../public/upload");

async function uploadFiles(ctx) {
try {
const imagesList = await ctx.db.EXCUTE(selectAllImagesQuery, []);
const form = formidable({
uploadDir: uploadDirPath,
keepExtensions: true,
multiples: true
});

form.parse(ctx.req, async (parseErr, fields, files) => {
  if(parseErr) {
    throw parseErr;
  }

  const insertedRows = [];
  const updatedImageNames = [];

  for(const fileKey in files) {
    const fileData = files[fileKey];
    let count = 1;

    const matchingImagesByName = imagesList.filter(image => image.image_name === fileData.originalFilename);

    if(matchingImagesByName.length > 0) {
      const originalNameParts = fileData.originalFilename.split(".");
      originalNameParts[0] += count++;

      const newFileName = originalNameParts.join(".");
      updatedImageNames.push(newFileName);

      const insertResult = await ctx.db.EXECUTE("INSERT INTO image (image_name, image_size, image_type, image_path) VALUES (?, ?, ?, ?)", [
        newFileName,
        fileData.size,
        fileData.mimetype,
        `http://localhost:3000/getFile/${newFileName}`
      ]);
      insertedRows.push(insertResult);
      fs.renameSync(fileData.filepath, path.join(uploadDirPath, newFileName));
    } else {
      insertedRows.push(await ctx.db.EXECUTE("INSERT INTO image (image_name, image_size, image_type, image_path) VALUES (?, ?, ?, ?)", [
        fileData.originalFilename,
        fileData.size,
        fileData.mimetype,
        `http://localhost:3000/getFile/${fileData.originalFilename}`
      ]));
      fs.renameSync(fileData.filepath, path.join(uploadDirPath, fileData.originalFilename));
    }
  }

  const { infoList } = await getList(ctx);
  ctx.body = { code: "200", msg: "全部上传成功", infoList };
});
} catch (error) {
console.error(error);
ctx.body = { code: "500", msg: "出现错误，上传失败" };
}
}
async function readPortrait(ctx) {
  const url = path.join(__dirname, "../public/portrait");
  const sql = "select user_portrait from users where user_id = ?";
  const sql1 = "update users set user_portrait = ? where user_id = ?";
  const result1 = await ctx.db.EXCUTE(sql, [ctx.params.id]);
  
  const form = formidable({
    uploadDir: url,
    keepExtensions: true,
    multiples: true
  });
  
  try {
    const files = await new Promise((resolve, reject) => {
      form.parse(ctx.req, (err, fields, files) => {
        if (err) {
          reject(err);
        } else {
          resolve(files);
        }
      });
    });
    
    const res = await ctx.db.EXCUTE(sql1, [files[0].originalFilename, ctx.params.id]);
    fs.renameSync(files[0].filepath, path.join(url, files[0].originalFilename));
    
    ctx.body = { code: "200", msg: "上传成功", url: files[0].originalFilename };
    rv(123);
  
  } catch (err) {
    // handle error
  }
}

const option = {
  size: 4,
  noise: 1,
  height: 40,
  color: true
  };
  
  router.get("/getAuth", async (ctx, next) => {
  const captcha = svgCaptcha.create(option);
  ctx.session.captcha = captcha.text;
  ctx.body = captcha;
  });
  
  router.get("/getPortrait/:id", async (ctx, next) => {
  const url = path.join(__dirname, "../public/portrait/" + ctx.params.id);
  const data = fs.readFileSync(url);
  ctx.body = data;
  });
  
  router.post("/getList" , async(ctx, next) => {
  const page = ctx.request.body.page;
  const arr = await getImgInfo(ctx);
  const length = arr.length;
  const obj = {
  code: 200,
  msg: "成功获取数据",
  infoList: arr.slice((page - 1) * 10 , page * 10),
  total: length
  };
  ctx.body = obj;
  });
  
  router.post("/submit" , async (ctx, next) => {
  const sql = "select user_name, user_password from users";
  const result = await ctx.db.EXCUTE(sql, []);
  const sql1 = "select * from users where user_name = ? and user_password = ?";
  const { auth, username, password } = ctx.request.body;
  
  if (nowCaptcha.text === auth) {
  const match = result.find(item => item.user_name === username && item.user_password === password);
  
  if (match) {
    const token = jwt.sign({ username, authority: true }, mykey);
    const userInfo = await ctx.db.EXCUTE(sql1, [username, password]);
    ctx.body = { code: 200, type: "success", message: "登录成功", token, userInfo };
  } else {
    ctx.body = { code: 500, type: "error", message: "用户名或密码错误" };
  }
  } else {
  ctx.body = { code: 500, type: "error", message: "验证码错误" };
  }
  });
  const Router = require('koa-router');
  const fs = require('fs');
  
  router.post('/', async (ctx, next) => {
  let checkRes = await checkToken(ctx);
  if(checkRes) {
  const files = ctx.request.files;
  const image = files && files.image;
  
  if (!image) {
    ctx.status = 400
    return ctx.body = { success: false, error: '缺少图片' }
  }
  
  const reader = fs.createReadStream(image.path);
  const fileName = `${Date.now()}-${image.name}`;
  const filePath = `public/upload/${fileName}`;
  const upStream = fs.createWriteStream(filePath);
  
  reader.pipe(upStream);
  
  const infoList = await getImageInfo();
  ctx.body = { code: "200", message: "上传成功", infoList };
  } else {
  ctx.status = 401;
  ctx.body = {code: "500", msg: "验证没有通过"};
  }
  });
  
  router.get('/', async (ctx, ) => {
  const url = path.join(__dirname, "../public/upload");
  const list = fs.readdirSync(url);
  ctx.body = list;
  });
  
  router.get('/:fileName', async(ctx, ) => {
  let url = path.join(__dirname, "../public/upload");
  ctx.set('Content-Type', 'image/png');//或者其他的文件类型
  ctx.body = fs.readFileSync(path.join(url, ctx.params.fileName));
  });
  
  router.get('/list', async(ctx, ) => {
  ctx.body = await getImageInfo();
  });
  
  router.delete('/:fileName', async(ctx) => {
  let checkRes = await checkToken(ctx);
  if(checkRes) {
  let url = path.join(__dirname, "../public/upload");
  let sql = "delete from image where name = ?";
  let result = await ctx.db.EXCUTE(sql, [fileName]);
  fs.unlinkSync(path.join(url, fileName));
  const infoList = await getImageInfo();
  ctx.body = { code: 200, msg: "成功删除", infoList };
  } else {
  ctx.status = 401;
  ctx.body = {code: "500", msg: "验证没有通过"};
  }
  });
  
  const getImageInfo = async() => {
  let sql = "select * from image";
  let result = await ctx.db.EXECUTE(sql, []);
  return result.reverse();
  }

module.exports = router